const { Service } = require('egg');
const myDate = require('../utils/myDate');
const { sendEmail } = require('../utils/email');
const { emailThrottleDuration } = require('../config/index');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
class MeetingService extends Service {
  async addMeeting(meetingInfo) {
    meetingInfo.create_time = myDate.getNowDate();
    meetingInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    meetingInfo.create_by = userInfo.id;
    meetingInfo.update_by = userInfo.id;
    const res = await this.app.mysql.insert('meeting', {
      name: meetingInfo.name,
      create_by: userInfo.id,
      update_by: userInfo.id,
      create_time: myDate.getNowDate(),
      update_time: myDate.getNowDate(),
    });
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async updateMeeting(meetingInfo) {
    meetingInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    meetingInfo.update_by = userInfo.id;
    const target = {
      name: meetingInfo.name,
      update_by: userInfo.id,
      update_time: myDate.getNowDate(),
    };
    if (meetingInfo.score_panel) {
      target.score_panel = meetingInfo.score_panel;
    }
    const res = await this.app.mysql.update(
      'meeting',
      target,
      { where: { id: meetingInfo.id } }
    );
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async getMeetings(pageNum, pageSize, name) {
    let where = '';
    if (name) {
      where = `WHERE name LIKE '%${name}%'`;
    }
    const total = await this.app.mysql.count('meeting', where);
    const res = await this.app.mysql.query(
      `SELECT * FROM meeting ${where} LIMIT ?, ?`,
      [ (pageNum - 1) * pageSize, pageSize ]
    );
    if (res) {
      return {
        meetings: res,
        total,
      };
    }
    return false;
  }

  async getMeeting(id) {
    const res = await this.app.mysql.get('meeting', { id });
    if (res) {
      const users = await this.app.mysql.query(
        `SELECT u.* 
        FROM meeting_user mt 
        JOIN user u ON u.id = mt.user_id
        where mt.meeting_id = ${res.id}`
      );
      const interviews = await this.app.mysql.query(
        `SELECT i.id,i.is_send_offer,i.interviewer_id,i.user_id,i.meeting_id,i.begin,i.end,i.is_send_email,i.state,i.create_by,i.update_by,u.name,u.home,u.email,u.phone,u.sex,u.birth_day,i.evoluation
        FROM interview i 
        JOIN user u ON u.id = i.user_id
        WHERE i.meeting_id = ${res.id}`
      );
      interviews.forEach(item => {
        item.evoluation = item.evoluation ? JSON.parse(item.evoluation) : null;
      });
      return {
        res,
        users,
        interviews,
      };
    }
    return false;
  }

  async delMeeting(ids) {
    const res = await this.app.mysql.query(
      `delete from meeting where id in (${ids.join(',')})`
    );
    await this.app.mysql.query(
      `delete from meeting_user where meeting_id in (${ids.join(',')})`
    );
    await this.app.mysql.query(
      `delete from interview where meeting_id in (${ids.join(',')})`
    );
    if (res.affectedRows) {
      return {
        state: true,
        msg: '删除成功',
      };
    }
    return {
      state: false,
      msg: '删除失败',
    };
  }

  async addMeetingUsers(meetingId, userIds) {
    for (const id of userIds) {
      const isExit = await this.app.mysql.query(
        `SELECT * FROM meeting_user WHERE meeting_id = ${meetingId} AND user_id = ${id}`
      );
      if (isExit.length) {
        continue;
      }
      const res = await this.app.mysql.query(
        `INSERT INTO meeting_user (meeting_id, user_id) VALUES (${meetingId}, ${id})`
      );
      if (!res) {
        return {
          state: false,
          msg: '添加失败',
        };
      }
    }
    await this.ctx.service.meeting.updateInterView(meetingId);
    return {
      state: true,
      msg: '添加成功',
    };
  }

  async delMeetingUsers(meetingId, userIds) {
    const res = await this.app.mysql.query(
      `delete from meeting_user 
      where meeting_id = ${meetingId} 
      and user_id in (${userIds.join(',')})`
    );
    await this.ctx.service.meeting.updateInterView(meetingId);
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async updateInterView(meetingId) {
    const curUser = await this.app.mysql.query(
      `SELECT user_id FROM meeting_user WHERE meeting_id = ${meetingId}`
    );
    const userIds = curUser.map(item => item.user_id);
    if (userIds.length) {
      await this.app.mysql.query(
        `delete from interview where meeting_id = ${meetingId} and user_id not in (${userIds.join(
        )})`
      );
    } else {
      await this.app.mysql.query(
        `delete from interview where meeting_id = ${meetingId}`
      );
      return;
    }
    for (let i = 0; i < userIds.length; i++) {
      const isExit = await this.app.mysql.query(
        `SELECT * FROM interview WHERE meeting_id = ${meetingId} AND user_id = ${userIds[i]}`
      );
      if (isExit.length) {
        continue;
      }
      const tencent_num = Math.floor(100000 + Math.random() * 900000);
      await this.app.mysql.query(
        `INSERT INTO interview (meeting_id, user_id, state, tencent_num) VALUES (${meetingId}, ${userIds[i]}, '0', ${tencent_num})`
      );
    }
  }

  async sendEmail(meetingId, userId) {
    // const isSend = await this.ctx.service.redis.get(`send-interview-email${meetingId}${userId}`);
    // if (isSend) {
    //   return {
    //     state: false,
    //     msg: '冷却中，请稍后再试试',
    //   };
    // }
    await this.ctx.service.redis.set(`send-interview-email${meetingId}${userId}`, true, emailThrottleDuration);
    const interview = await this.app.mysql.query(
      `SELECT * FROM interview WHERE meeting_id = ${meetingId} AND user_id = ${userId}`
    );
    if (!interview[0].begin || !interview[0].end) {
      return {
        state: false,
        msg: '面试时间未设置',
      };
    }
    if (!interview[0].interviewer_id) {
      return {
        state: false,
        msg: '面试官未设置',
      };
    }
    let uniqueId = '';
    if (Number(interview[0].is_send_email) !== 1) {
      uniqueId = this.app.jwt.sign({ id: userId, meetingId }, this.app.config.jwt.secret);
      await this.app.mysql.query(
        `UPDATE interview 
        SET is_send_email = '1', token = '${uniqueId}'
        WHERE meeting_id = ${meetingId} AND user_id = ${userId};`
      );
    } else {
      uniqueId = interview[0].token;
    }

    const meetData = await this.app.mysql.query(
      `SELECT * FROM meeting WHERE id = ${meetingId}`
    );
    const userData = await this.app.mysql.query(
      `SELECT * FROM user WHERE id = ${userId}`
    );
    const userEmail = userData[0].email;
    const htmlContent = `
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>面试邀请</title>
    </head>
    <body>
        <p>亲爱的${userData[0].name} 同学，您好！</p>
        <p>感谢关注PANDA校园招聘！现诚邀您参加${meetData[0].name}职位的视频面试。</p>
        <p>视频面试时请您尽量使用电脑端进行操作（大于73版本的Chrome内核浏览器或者firefox、opera浏览器），并打开相机权限。</p>
        <ul>
            <li>面试日期：2025年3月4日星期二</li>
            <li>面试时间：17:00</li>
            <li>面试时长：45分钟（可能视面试情况缩减或延长，请预留一定缓冲时间）</li>
            <li>面试形式：视频面试</li>
            <li>面试地址：http://localhost:4666/login?token=${uniqueId}</li>
        </ul>
        <h3>【注意】</h3>
        <ol>
            <li>如确定参加面试，请点击“参加”。</li>
            <li>如时间冲突，请点击“拒绝”，并反馈可面试时间。</li>
        </ol>
        <p>有任何问题，请联系hr: 17338763009</p>
        <p>请您确认是否参加</p>
        <p><a href="http://localhost:4666/wait?status=accept&key=${uniqueId}" style="background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none;">参加 / Yes</a> 
        <a href="http://localhost:4666/wait?status=reject&key=${uniqueId}" style="background-color: #6c757d; color: white; padding: 10px 20px; text-decoration: none;">不参加 / No</a> 
        </p>
    </body>
    </html>
    `;
    const res = await sendEmail(userEmail, 'PANDA校园招聘——应届生面试邀请函', htmlContent);
    if (res) {
      return {
        state: true,
        msg: '发送成功',
      };
    }
    return {
      state: false,
      msg: '发送失败',
    };
  }

  async getToken(email, key) {
    const isExit = await this.app.mysql.get('user', { email });
    if (!isExit) {
      return {
        state: false,
        msg: '用户不存在',
      };
    }
    const isMeetingExit = await this.app.mysql.get('interview', { user_id: isExit.id, token: key });
    if (!isMeetingExit) {
      return {
        state: false,
        msg: '面试户不存在',
      };
    }
    const token = this.app.jwt.sign({
      id: isExit.id,
      interviewId: isMeetingExit.id,
      meetingId: isMeetingExit.meeting_id,
    }, this.app.config.jwt.secret);
    return {
      state: true,
      data: {
        token: `Bearer ${token}`,
      },
    };
  }

  async updateInterViewTime(interview) {
    const target = { id: interview.interviewId, begin: interview.begin, end: interview.end };
    if (interview.interviewer_id) {
      target.interviewer_id = interview.interviewer_id;
    }
    const update = await this.app.mysql.update('interview', target);
    if (update) {
      return {
        state: true,
        msg: '修改成功',
      };
    }
    return {
      state: false,
      msg: '修改失败',
    };
  }

  async getByToken(meetingId, userId) {
    const res = await this.app.mysql.query(
      `SELECT i.*,u.name as user_name,m.name AS meeting_name
      FROM interview i
      JOIN user u ON u.id = i.user_id
      JOIN meeting m ON m.id = i.meeting_id
      WHERE i.meeting_id = ${meetingId} AND i.user_id = ${userId}`);
    if (res) {
      return res[0];
    }
    return false;
  }

  async getInterviewById(interviewId) {
    const res = await this.app.mysql.get('interview', { id: interviewId });
    if (res) {
      return res;
    }
    return false;
  }

  async updateState(key, is_reject) {
    const isExit = await this.app.mysql.get('interview', { token: key });
    if (!isExit) {
      return {
        state: false,
        msg: '面试不存在',
      };
    }
    const updateRes = await this.app.mysql.update('interview', { id: isExit.id, is_reject });
    if (updateRes.affectedRows) {
      return true;
    }
    return false;
  }

  async getIsReject(key) {
    const isExit = await this.app.mysql.get('interview', { token: key });
    if (!isExit) {
      return {
        state: false,
        msg: '面试不存在',
      };
    }
    const state = await this.app.mysql.get('interview', { id: isExit.id });
    return state;
  }

  async getInterView(userId, day) {
    const res = await this.app.mysql.query(
      `SELECT i.*,u.name as user_name,m.name AS meeting_name
      FROM interview i
      JOIN user u ON u.id = i.user_id
      JOIN meeting m ON m.id = i.meeting_id
      WHERE i.interviewer_id = ${userId} AND DATE_FORMAT(begin, '%Y-%m-%d') = '${day}'`
    );
    if (res) {
      return res;
    }
    return false;
  }

  async getEvaluation(meetingId) {
    const res = await this.app.mysql.get('meeting', { id: meetingId });
    if (res) {
      return res.score_panel;
    }
    return false;
  }

  async getEvaluations(interviewer_id) {
    const res = await this.app.mysql.query(
      `SELECT *
      FROM interview
      WHERE update_by = ${interviewer_id}`
    );
    if (res) {
      return res;
    }
    return false;
  }

  async submitEvaluation(userId, interviewId, evoluation) {
    const res = await this.app.mysql.query(
      `UPDATE interview SET evoluation = '${evoluation}',update_by = ${userId} WHERE id = ${interviewId}`
    );
    if (res) {
      return true;
    }
    return false;
  }

  async getEvaluationByEid(interviewId) {
    const res = await this.app.mysql.query(
      `SELECT i.*,u.name as uname,m.name AS mname
      FROM interview i
      JOIN user u ON u.id = i.user_id
      JOIN meeting m ON m.id = i.meeting_id
      WHERE i.id = '${interviewId}'`
    );
    if (res) {
      return res;
    }
    return false;
  }

  async uploadjl(userId, interviewId, file) {
    try {
      const targetDir = path.join(this.app.baseDir, 'app/public/jlFiles');
      await mkdirp(targetDir);

      const now = Date.now();
      // 保存新文件
      const targetPath = path.join(targetDir, `${now}.pdf`);
      const reader = fs.createReadStream(file.filepath);
      const writer = fs.createWriteStream(targetPath);

      await new Promise((resolve, reject) => {
        reader.pipe(writer);
        writer.on('finish', resolve);
        writer.on('error', reject);
      });

      const res = await this.app.mysql.query(
        `UPDATE interview SET jl_file = '${now}.pdf' WHERE id = ${interviewId} AND user_id = ${userId}`
      );
      console.log(res, 'res=======');

      if (res.affectedRows > 0) {
        return true;
      }
      return false;

    } catch (error) {
      return false;
    }
  }

  async accept(interviewId, isAccept) {
    const res = await this.app.mysql.query(
      `UPDATE interview SET is_reject = ${!isAccept} WHERE id = ${interviewId}`
    );
    if (res) {
      return true;
    }
    return false;
  }

  async getjl(userId, interviewId) {
    const res = await this.app.mysql.query(
      `SELECT jl_file FROM interview WHERE id = ${interviewId} AND user_id = ${userId}`
    );
    try {
      const targetDir = path.join(this.app.baseDir, 'app/public/jlFiles');
      const targetPath = path.join(targetDir, res[0].jl_file);
      const exists = fs.existsSync(targetPath);

      if (!exists) {
        return {
          exists: false,
          filePath: null,
          fileContent: null,
        };
      }

      const fileContent = await fs.promises.readFile(targetPath);
      return fileContent;
    } catch (error) {
      this.ctx.logger.error('获取文件失败:', error);
      return false;
    }
  }

  async getEvaluationById(id) {
    const res = await this.app.mysql.query(
      `SELECT 
      i.*,
      u.name AS uname,
      m.name AS mname
      FROM interview i
      JOIN user u ON u.id = i.user_id
      JOIN meeting m ON m.id = i.meeting_id
      WHERE i.update_by = ${id} `
    );
    if (res) {
      return res;
    }
    return false;
  }

  async sendOffer(interviewId) {
    await this.app.mysql.query(
      `UPDATE interview SET is_send_offer = 1 WHERE id = ${interviewId}`
    );
    const resData = await this.app.mysql.query(
      `SELECT * FROM interview WHERE id = ${interviewId}`
    );
    const userData = await this.app.mysql.query(
      `SELECT * FROM user WHERE id = ${resData[0].user_id}`
    );
    const meetData = await this.app.mysql.query(
      `SELECT * FROM meeting WHERE id = ${resData[0].meeting_id}`
    );
    const userEmail = userData[0].email;
    const htmlContent = `<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>录用通知</title>
</head>
<body>
    <p>亲爱的${userData[0].name} 同学，您好！</p>
    <p>非常感谢您对 PANDA 校园招聘的关注与参与。经过我们严格的评估和筛选，现正式向您发出录用邀请，诚邀您加入我们的团队，担任${meetData[0].name} 职位。</p>
    <h3>【职位详情】</h3>
    <ul>
        <li>职位名称：${meetData[0].name}</li>
        <li>部门：软件开发部</li>
        <li>工作地点：福建莆田</li>
    </ul>
    <h3>【薪资福利】</h3>
    <ul>
        <li>福利待遇：五险一金、带薪年假、节日福利等</li>
    </ul>
    <h3>【注意事项】</h3>
    <ol>
        <li>请在收到本通知后的 7 个工作日内，点击“接受 offer”进行确认。若逾期未确认，将视为自动放弃该录用机会。</li>
        <li>请在入职前准备好相关材料，如身份证、学历证书等原件及复印件。</li>
    </ol>
    <p>如果您有任何疑问，请随时联系我们的 HR：17338763009。</p>
    <p>期待您的加入，与我们一同创造美好未来！</p>
</body>
</html>`;
    const send = await sendEmail(userEmail, 'PANDA校园招聘', htmlContent);
    if (send) {
      return true;
    }
    return false;
  }

  async sendNoOffer(interviewId) {
    await this.app.mysql.query(
      `UPDATE interview SET is_send_offer = 1 WHERE id = ${interviewId}`
    );
    const resData = await this.app.mysql.query(
      `SELECT * FROM interview WHERE id = ${interviewId}`
    );
    const userData = await this.app.mysql.query(
      `SELECT * FROM user WHERE id = ${resData[0].user_id}`
    );
    const meetData = await this.app.mysql.query(
      `SELECT * FROM meeting WHERE id = ${resData[0].meeting_id}`
    );
    const userEmail = userData[0].email;
    const htmlContent = `
   <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>面试结果通知</title>
</head>
<body>
    <p>亲爱的${userData[0].name} 同学，您好！</p>
    <p>非常感谢您对 PANDA 校园招聘的关注与参与。经过我们认真的评估和筛选，很遗憾地通知您，您此次应聘${meetData[0].name} 职位未通过。</p>
    <p>本次招聘竞争非常激烈，有众多优秀的候选人参与，我们此次选择了与岗位要求更加匹配的人选。但您在面试过程中展现出的能力和素质也给我们留下了深刻的印象。</p>
    <p>我们鼓励您继续关注 PANDA 的后续招聘信息，未来可能还有适合您的机会。同时，您也可以持续提升自己的专业技能和综合素质，相信您在未来的求职道路上会取得更好的成绩。</p>
    <p>如果您对此次面试结果有任何疑问，欢迎随时联系我们的 HR：17338763009。</p>
    <p>再次感谢您的支持与理解，祝您生活愉快，一切顺利！</p>
</body>
</html>`;
    const send = await sendEmail(userEmail, 'PANDA校园招聘', htmlContent);
    if (send) {
      return true;
    }
    return false;
  }
}

module.exports = MeetingService;
